# TDS传感器
from machine import Pin, ADC
import math

'''
    TDS传感器水质监测
'''


class TDSSensor:
    temperature = 25  # 温度
    VREF = 3.3  # analog reference voltage(Volt) of the ADC
    SCOUNT = 50
    analogSampleTimepoint = 0
    analogBuffer = []

    adc = ADC(Pin(32))  # 注意：ADC 功能在引脚 32-39（ADC 模块 1）和 引脚 0、2、4、12-15 和 25-27（ADC 模块 2）
    adc.atten(ADC.ATTN_11DB)  # 设置衰减比 满量程3.3v
    adc.width(ADC.WIDTH_12BIT)  # 设置数据宽度为12bit，12位的分辨率最大值是4096个不同的电压即从0-4095

    # 中值滤波
    @staticmethod
    def get_median_num(bArray: list):
        orted_numbers = sorted(bArray)  # 排序
        num_length: int = len(orted_numbers)
        if (num_length & 1) > 0:  # 奇数长度
            median_num = orted_numbers[math.floor((num_length - 1) / 2)]
        else:
            median_num = (orted_numbers[math.floor(num_length / 2)] + orted_numbers[math.floor(num_length / 2 - 1)]) / 2
        return median_num

    @staticmethod
    def get_tds():
        ad = 0
        for i in range(TDSSensor.SCOUNT):  # 均值滤波  读取50次数值
            ad += (TDSSensor.adc.read())
        ad = ad / TDSSensor.SCOUNT  # 取其平均值
        average_voltage = float(ad) * TDSSensor.VREF / 4096.0  # AD转换
        # temperature compensation formula: fFinalResult(25^C) = fFinalResult(current)/(1.0+0.02*(fTP-25.0));
        compensation_coefficient: float = 1.0 + 0.02 * (TDSSensor.temperature - 25.0)
        compensation_volatge: float = average_voltage / compensation_coefficient  # temperature compensation
        # convert voltage value to tds value
        tds_value = (133.42 * compensation_volatge * compensation_volatge * compensation_volatge - 255.86 *
                     compensation_volatge * compensation_volatge + 857.39 * compensation_volatge) * 0.5
        return tds_value
